package com.edu.imau;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ljx
 * @date 2023/1/2 15:22
 */
@WebFilter("/*")
public class FilterX implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpSession session=req.getSession();
        String path=req.getServletPath();
//        System.out.println(session.getAttribute("login_status"));
        if(path.contains("index.jsp") || path.contains("Login")|| path.contains("zc.css")) {
            filterChain.doFilter(servletRequest,servletResponse);
        } else {
            if ("OK".equals(session.getAttribute("login_status"))) {
                filterChain.doFilter(servletRequest,servletResponse);
            } else {
                String error_msg="you need to login first!";
                req.setAttribute("msg",error_msg);
                req.getRequestDispatcher("index.jsp").forward(req,servletResponse);
            }
        }

    }

    @Override
    public void destroy() {
//        System.out.println("destroy");
    }
}
